Power Automate workflow from SPFx NOT as Anyone
In many scenarios, Power Automate flows are triggered automatically, such as when a list item is created or updated, when a file is uploaded, or when a scheduled event occurs. However, there are times when we want to trigger a flow programmatically from within our SPFx web part.
In this article, we’ll explore how to trigger a Power Automate directly from an SPFx web part using an authenticated HTTP request, without exposing the flow as an anonymous endpoint.
This approach protects your tenant, ensures secure execution, and gives you full control over who is allowed to trigger the workflow.
In this article, we’ll explore how to trigger a Power Automate workflow directly from an SPFx web part using an authenticated HTTP request, without exposing the flow as an anonymous endpoint.
This approach protects your tenant, ensures secure execution, and gives you full control over who is allowed to trigger the workflow.
Solution: Use “Any user in my tenant” or “Specific users in my tenant”.
Prerequisites
- SharePoint Online tenant with app catalog and SPFx enabled
- Permission to create Instant cloud flows in Power Automate
- Permission to create / manage Entra ID (Azure AD) app registrations
- SPFx development environment (Node, Yeoman generator, etc.)
Build the Power Automate Flow
First, we’ll create a simple flow that accepts two strings and echoes them back in the response.
Request Body JSON Schema
{
"type": "object",
"properties": {
"stringone": {
"type": "string"
},
"stringtwo": {
"type": "string"
}
}
}
This allows your SPFx web part to send a JSON payload containing stringone and
stringtwo.
Add a Response action:
- Status code:
200 - Body: dynamic content →
Body
Copy the HTTP URL from the trigger — this will be used in SPFx.
Now that Power Automate is fully configured, let’s take a look at our SPFx solution in action
Core Component Analysis
The solution is composed of three core parts:
- PowerAutomateSpfxWebPart.ts – The main web part class handling initialization and authentication
- PowerAutomateSpfx.tsx – The React component providing the user interface
- package-solution.json – Configuration file defining required API permissions
Component Structure
The PowerAutomateSpfx component is a class-based React component that provides an intuitive interface
for triggering Power Automate flows from SharePoint:
interface IPowerAutomateSpfxState {
responseMessage: string;
isLoading: boolean;
}
export default class PowerAutomateSpfx extends React.Component<IPowerAutomateSpfxProps, IPowerAutomateSpfxState>
1. State Management
The component manages two crucial state properties:
responseMessage: Displays API responses or error messagesisLoading: Controls button state and loading indicators
2. Flow Trigger Handler
The heart of the integration lies in the handleTriggerFlow method:
private handleTriggerFlow = async (): Promise<void> => {
this.setState({ isLoading: true, responseMessage: 'Triggering flow...' });
const requestBody = {
Title: 'Test from SPFx',
UserEmail: this.props.userEmail
};
try {
const response = await this.props.triggerFlow(requestBody, this.props.url);
this.setState({
isLoading: false,
responseMessage: `Success: ${JSON.stringify(response, null, 2)}`
});
} catch (error: any) {
this.setState({
isLoading: false,
responseMessage: `Error: ${error.message || 'Unknown error occurred'}`
});
}
}
This method:
- Sets loading state to provide user feedback
- Constructs a request payload with user context
- Delegates the actual API call to the parent web part
- Handles both success and error scenarios gracefully
3. User Interface Design
The render method creates a responsive interface that:
- Displays user information and environment context
- Shows the configured Flow URL
- Provides a prominent trigger button with loading states
- Displays formatted API responses in a monospace container
<button
type="button"
onClick={() => this.handleTriggerFlow()}
disabled={this.state.isLoading}
style={{
padding: '10px 20px',
backgroundColor: this.state.isLoading ? '#ccc' : '#0078d4',
color: 'white',
border: 'none',
borderRadius: '3px',
cursor: this.state.isLoading ? 'not-allowed' : 'pointer'
}}
>
{this.state.isLoading ? 'Processing...' : 'Trigger Power Automate Flow'}
</button>
Props Interface Design
The component's props interface demonstrates thoughtful design for SPFx integration:
export interface IPowerAutomateSpfxProps {
url: string;
isDarkTheme: boolean;
environmentMessage: string;
hasTeamsContext: boolean;
userDisplayName: string;
userEmail: string;
triggerFlow: (body: any, flowUrl: string) => Promise<any>;
}
Authentication and API Integration
Web Part Implementation
The PowerAutomateSpfxWebPart.ts file handles the complex authentication logic:
private triggerFlow = async (body: any, flowUrl: string): Promise<any> => {
try {
const client = await this.context.aadHttpClientFactory
.getClient('https://service.flow.microsoft.com/');
const response = await client.post(flowUrl, AadHttpClient.configurations.v1, {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify(body)
});
if (response.ok) {
const responseData = await response.json();
console.log('Flow triggered successfully', responseData);
return responseData;
} else {
const errorText = await response.text();
console.error('Flow trigger failed', response.status, response.statusText, errorText);
throw new Error(`HTTP ${response.status}: ${response.statusText}${errorText ? ' - ' + errorText : ''}`);
}
} catch (error) {
console.error('Error calling flow', error);
throw error;
}
}
This implementation:
- Uses
AadHttpClientFactoryfor Azure AD authentication - Targets the Microsoft Flow Service endpoint
- Implements comprehensive error handling
- Returns structured response data
API Permissions Setup
The package-solution.json file contains a crucial configuration for Power Automate integration:
{
"solution": {
"name": "power-automate-spfx-client-side-solution",
"id": "808c9e90-6714-4ae5-8b5c-c96b1410220b",
"version": "1.0.0.0",
"includeClientSideAssets": true,
"skipFeatureDeployment": true,
"isDomainIsolated": false,
"developer": {
"webApiPermissionRequests": [
{
"resource": "Microsoft Flow Service",
"scope": "User"
}
]
}
}
}
Packaging and Deployment
Run the production build:
gulp bundle --ship
gulp package-solution --ship
Upload .sppkg to the App Catalog, grant permissions, configure the property pane with your flow URL, and test.
Conclusion
This solution is an excellent starting point for securely bridging SPFx and Power Automate. It demonstrates best practices and provides a solid foundation for more advanced integration scenarios.
View the sample resources on GitHub: Execute Power Automate workflow from SPFx – GitHub Resources